<?php

class Consolium {

    private $arrRawArgs;
    private $hKeyValueArgs;

    private $sProgramName;

    /**
     * @return Consolium
     */
    private static function getInstance() {
        static $instance = null;
        if ($instance === null) {
            $instance = new self;
        }
        return $instance;
    }

    private function __construct() {

        if (empty($_SERVER['argv'])) {
            $this->sProgramName = '';
            $this->arrRawArgs = array();
        } else {
            $this->sProgramName = $_SERVER['argv'][0];
            $this->arrRawArgs = array_slice($_SERVER['argv'],1);
        }

        $numArgs = count($this->arrRawArgs);

        for ($i = 0; $i < $numArgs; $i++) {

            $sArg = $this->arrRawArgs[$i];

            if ($sArg[0] == '-') {

                if (($i != ($numArgs - 1)) &&
                    ($this->arrRawArgs[$i + 1][0] != '-')
                ) {
                    $sArgValue = $this->arrRawArgs[$i + 1];
                    $i++;
                } else {
                    $sArgValue = '';
                }

                $this->hKeyValueArgs[$sArg] = $sArgValue;
            }
        }
    }

//    public function hasValueArgument($sArgName) {
//
//    }

    public static function getProgramName() {
        return self::getInstance()->doGetProgramName();
    }

    private function doGetProgramName() {
        return $this->sProgramName;
    }

//    /**
//     * Like "-user 12" (arg/value pair) or "-user" (key only);
//     */
//    public function hasArgument($sArgName, $sArgAlias = null) {
//        return isset($this->hKeyValueArgs[$sArgName]);
//    }

    public static function hasNotEmptyArgument($sArgName, $sArgAlias = null) {
        return self::getInstance()->doHasNotEmptyArgument($sArgName, $sArgAlias);
    }
    /**
     * Like "-user 12" only
     */
    private function doHasNotEmptyArgument($sArgName, $sArgAlias = null) {

        if (!empty($this->hKeyValueArgs[$sArgName]))
            return true;

        if (!empty($this->hKeyValueArgs[$sArgAlias]))
            return true;

        return false;
    }

    public static function getArgumentValue($sArgName, $sArgAlias = null) {
        return self::getInstance()->doGetArgumentValue($sArgName, $sArgAlias);
    }

    private function doGetArgumentValue($sArgName, $sArgAlias = null) {

        if (!empty($this->hKeyValueArgs[$sArgName]))
            return $this->hKeyValueArgs[$sArgName];

        if (!empty($this->hKeyValueArgs[$sArgAlias]))
            return $this->hKeyValueArgs[$sArgAlias];

        throw new ConsoleArgumentException("Argument $sArgName has no value");
    }
}

class ConsoleArgumentException extends Exception {}

?>